import React from 'react';
import Chart from 'bizcharts/lib/components/Chart';
import Axis from 'bizcharts/lib/components/Axis';
import Geom from 'bizcharts/lib/components/Geom';
import Legend from 'bizcharts/lib/components/Legend';
import Tooltip from 'bizcharts/lib/components/Tooltip';
import DataSet from '@antv/data-set';
import { connect } from 'dva/index';
import { Button, Col, Form, Input, message, Modal, Popconfirm, Radio, Row, Select, Table, Tabs } from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../common/rightBox';
import RoleSelect from "../common/roleSelect";
import ProductDetail from './productDetail';
import MarketDetail from './marketDetail';
import BizParams from '../common/BizParams';

const R = require('ramda');
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;

const companyDetail = Form.create({ wrappedComponentRef: true })(class CompanyDetail extends React.Component {
    constructor(props) {
        super(props);
        this.initData(props.dataSource, true);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.dataSource)(nextProps.dataSource)) {
            this.initData(nextProps.dataSource)
        }
    }

    initData = (dataSource, flag) => {
        let productList = dataSource.productList ? dataSource.productList : []
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        if (flag) {
            this.state = {
                open: false,
                disabled: false,
                marketDisabled: false,
                isAllocation: false,        //判断是否分配操作员
                productList
            }
        } else {
            this.setState({
                productList
            })
        }
    }

    handleCancel = () => {
        this.setState({ open: false });
        this.props.form.resetFields();
        this.props.dispatch({
            type: 'company/cleanSource'//清空数据
        });
    }

    handleOpen = ({ disabled, id, marketDisabled, isAllocation }) => {
        let productList = this.props.dataSource && this.props.dataSource.productList && id ? this.props.dataSource.productList : [];
        this.setState({ open: true, disabled, productList, marketDisabled, isAllocation });
    }

    handleOpenProductDetail = (disabled, record) => {
        this.productDetail.handleOpen(disabled, record);
    }

    handleOpenMarketDetail = (disabled, record) => {
        this.props.dispatch({
            type: 'market/getMarketInfoById',
            payload: {
                id: record.id,
                onSuccess: (dataSource) => {
                    this.marketDetail.handleOpen(disabled, dataSource ? dataSource : { cid: record.cid });
                }
            }
        })
    }

    handleDeleteMarket = (record) => {
        this.props.dispatch({
            type: 'market/deleteMarketInfoById',
            payload: {
                id: record.id,
                onSuccess: (dataSource) => {
                    this.props.dispatch({
                        type: 'market/queryMarketListByCId',
                        payload: {
                            cId: record.cid,
                            page: this.props.market.page
                        }
                    })
                }
            }
        })
    }

    handleDeleteProduct = (record) => {
        let productList = R.difference(this.state.productList, [record]);
        this.setState({ productList });
    }

    handleAddOrUpdateProduct = (record) => {
        let productList = [];
        //修改逻辑
        R.map((product) => {
            if (product.id === record.id) {
                productList.push(record);
            } else {
                productList.push(product);
            }
        }, this.state.productList);
        //新增逻辑
        if (!R.contains(record, productList)) {
            productList.push(record);
        }
        this.setState({ productList });
    }

    handleSave = () => {
        this.props.form.validateFields({ force: true }, (errors, values) => {
            if (errors) return;
            if (!values.telephone && !values.mobile && !values.email && !values.qq && !values.wechat) {
                message.error("请至少填写一种联系方式");
                return;
            }
            values.serviceItem = R.isNil(values.serviceItem) ? null : R.join('|')(values.serviceItem);
            values.id = this.props.dataSource && this.props.dataSource.id ? this.props.dataSource.id : null;
            values.productList = this.state.productList;

            let dispatchType = values.id ? 'company/updateCompany' : 'company/createCompany';
            if (!R.equals(R.pick(Object.keys(values), this.props.dataSource), values)) {
                this.props.dispatch({
                    type: dispatchType,
                    payload: {
                        dataSource: values,
                        onSuccess: () => {
                            this.handleCancel();
                            if (this.props.refreshList) this.props.refreshList(true);
                        }
                    }
                })
            } else this.handleCancel();
        })
    }

    handleConfirm = () => {
        this.createProduct.handleConfirm();
    }

    handleChangeSource = (value) => {
        if(value !== "2") this.props.form.setFieldsValue({introducer: ""});
    }

    initColumns = () => {
        let columns = [
            { title: '产品名称', dataIndex: 'productName', key: 'productName' },
            { title: '产品数量', dataIndex: 'productQuantity', key: 'productQuantity' },
            { title: '产品规格', dataIndex: 'productModel', key: 'productModel' },
            { title: '备注', dataIndex: 'memo', key: 'memo' }
        ];
        if (!this.state.disabled) {
            columns.push(
                {
                    title: '操作', key: 'operator', render: (text, record, index) => {
                        let EditLink = <RightBox resource={RightConstants.COMPANY.COMPANY_PRODUCT_EDIT} split={true}><a href="#" onClick={this.handleOpenProductDetail.bind(this, false, record)}>编辑</a></RightBox>
                        let DeleteLink = <RightBox resource={RightConstants.COMPANY.COMPANY_PRODUCT_DELETE}><Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={this.handleDeleteProduct.bind(this, record)} okText="是" cancelText="否">
                            <a href="#">删除</a>
                        </Popconfirm></RightBox>
                        return (
                            <span>{EditLink}{DeleteLink}</span>
                        );
                    }
                }
            )
        }
        return columns;
    }

    marketColumns = [
        { title: '实际营销时间', dataIndex: 'market_time', key: 'market_time' },
        { title: '营销人员', dataIndex: 'creator_name', key: 'creator_name' },
        { title: '营销对象', dataIndex: 'market_object_name', key: 'market_object_name' },
        { title: '营销方式', dataIndex: 'market_mode_name', key: 'market_mode_name' },
        { title: '营销阶段', dataIndex: 'market_stage_name', key: 'market_stage_name' },
        { title: '成果定性', dataIndex: 'result_name', key: 'result_name' },
        {
            title: '操作', key: 'operator', render: (text, record, index) => {
                return (
                    <span>
                        <a href="#" onClick={this.handleOpenMarketDetail.bind(this, true, record)} >查看</a>
                        <span className="ant-divider" style={{ display: this.state.marketDisabled ? 'none' : 'inline-block' }} />
                        <RightBox resource={RightConstants.COMPANY.COMPANY_MARKETINFO_EDIT} split={true}><a href="#" onClick={this.handleOpenMarketDetail.bind(this, false, record)} style={{ display: this.state.marketDisabled ? 'none' : 'inline-block' }}>编辑</a></RightBox>
                        <RightBox resource={RightConstants.COMPANY.COMPANY_MARKETINFO_DELETE}><Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={this.handleDeleteMarket.bind(this, record)} okText="是" cancelText="否" style={{ display: this.state.marketDisabled ? 'none' : 'inline-block' }}>
                            <a href="#" style={{ display: this.state.marketDisabled ? 'none' : 'inline-block' }}>删除</a>
                        </Popconfirm></RightBox>
                    </span>
                );
            }
        }
    ]


    render() {

        const data = [
            { name: '当月利润', 'Jan.': 18.9, 'Feb.': 28.8, 'Mar.': 39.3, 'Apr.': 81.4, 'May': 47, 'Jun.': 20.3, 'Jul.': 24, 'Aug.': 35.6 },
            { name: '年利润', 'Jan.': 12.4, 'Feb.': 23.2, 'Mar.': 34.5, 'Apr.': 99.7, 'May': 52.6, 'Jun.': 35.5, 'Jul.': 37.4, 'Aug.': 42.4 }
        ];

        const dv = new DataSet.View();
        dv.source(data).transform({
            type: 'fold',
            fields: ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.'], // 展开字段集
            key: '月份', // key字段
            value: '业绩', // value字段
        });

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = { labelCol: { sm: { span: 8 } }, wrapperCol: { sm: { span: 14 } } };
        const layoutAddress = { labelCol: { sm: { span: 4 } }, wrapperCol: { sm: { span: 19 } } };
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;

        let attachmentMap = R.isNil(dataSource.attachmentMap) ? {} : dataSource.attachmentMap
        let hscodeList = R.isNil(this.props.hscode) || R.isEmpty(this.props.hscode) ? [] : this.props.hscode
        let productFacade = R.isNil(attachmentMap.productfacade) ? '' : attachmentMap.productfacade.url;
        let productBranchModel = R.isNil(attachmentMap.productbranchmodel) ? '' : attachmentMap.productbranchmodel.url;
        let productCartons = R.isNil(attachmentMap.productcartons) ? '' : attachmentMap.productcartons.url;
        let productOther = R.isNil(attachmentMap.productotherfile) ? '' : attachmentMap.productotherfile.url;

        let footer = [
            <Button key="save" size="large" loading={this.props.loading} onClick={this.handleSave.bind(this)} style={{ display: this.state.disabled ? 'none' : 'inline-block' }}>保存</Button>,
            <Button key="cancel" size="large" loading={this.props.loading} onClick={this.handleCancel.bind(this, true)}>{this.state.disabled ? "关闭" : "取消"}</Button>
        ];
        let columns = this.initColumns();
        return (
            <div>
                <Modal maskClosable={false} footer={footer} visible={this.state.open} title={"客户详情"} width={900} onCancel={this.handleCancel.bind(this)} closable={true}>
                    <Form>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="客户名称" hasFeedback>
                                    {getFieldDecorator('companyName', {
                                        rules: [{ required: true, message: '请输入客户名称！' }],
                                        initialValue: dataSource.companyName
                                    })(<Input disabled={this.state.disabled} maxLength="50" />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="客户简称" hasFeedback>
                                    {getFieldDecorator('shortname', {
                                        rules: [{
                                            required: true, message: '请输入客户简称！'
                                        }],
                                        initialValue: dataSource.shortname
                                    })(
                                        <Input disabled={this.state.disabled} maxLength="30" />
                                        )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="客户类型" hasFeedback>
                                    {getFieldDecorator('companyType', {
                                        rules: [{ required: true, message: '请选择客户类型！' }],
                                        initialValue: dataSource.companyType
                                    })(<BizParams disabled={this.state.disabled} sprCode="logisticsCompany" />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="服务项目" hasFeedback>
                                    {getFieldDecorator('serviceItem', {
                                        rules: [{ required: true, message: '请至少选择一个服务项目！' }],
                                        initialValue: R.isNil(dataSource.serviceItem) || R.isEmpty(dataSource.serviceItem) ? undefined : dataSource.serviceItem.split('|')
                                    })(<BizParams disabled={this.state.disabled} sprCode="serviceItem" mode="multiple" />)
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="客户来源" hasFeedback>
                                    {getFieldDecorator('cstOrigination', {
                                        initialValue: dataSource.cstOrigination,
                                        rules: [{
                                            required: true, message: '请选择客户来源',
                                        }]
                                    })(
                                        <Select disabled={this.state.disabled} onChange={this.handleChangeSource.bind(this)}>
                                            <Select.Option value="1">自主开发</Select.Option>
                                            <Select.Option value="2">转介绍</Select.Option>
                                        </Select>
                                        )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="介绍人" hasFeedback>
                                    {getFieldDecorator('introducer', {
                                        rules: [{
                                            required: this.props.form.getFieldValue("cstOrigination") === "2", message: '请输入介绍人！',
                                        }],
                                        initialValue: dataSource.introducer
                                    })(
                                        <Input disabled={this.state.disabled || this.props.form.getFieldValue("cstOrigination") === "1"} maxLength="50" />

                                        )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="客户性质" hasFeedback>
                                    {getFieldDecorator('cstProperty', {
                                        initialValue: dataSource.cstProperty,
                                        rules: [{
                                            required: true, message: '请选择客户性质',
                                        }]
                                    })(
                                        <RadioGroup disabled={this.state.disabled}>
                                            <Radio value="1">同行</Radio>
                                            <Radio value="2">直客</Radio>
                                        </RadioGroup>
                                        )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="结算方式" hasFeedback>
                                    {getFieldDecorator('statementType', {
                                        rules: [{
                                            required: true, message: '请选择结算方式！'
                                        }],
                                        initialValue: dataSource.statementType
                                    })(
                                        <RadioGroup disabled={this.state.disabled}>
                                            <Radio value="0">票结</Radio>
                                            <Radio value="1">月结</Radio>
                                        </RadioGroup>
                                        )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="等级" hasFeedback>
                                    {getFieldDecorator('level', {
                                        rules: [{ required: true, message: '请至少选择一个等级！' }],

                                        initialValue: dataSource.level
                                    })(
                                        <Select disabled={this.state.disabled}>
                                            <Select.Option value="1">优质</Select.Option>
                                            <Select.Option value="2">良好</Select.Option>
                                            <Select.Option value="3">普通</Select.Option>
                                            <Select.Option value="4">差</Select.Option>
                                        </Select>
                                        )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="合约号" hasFeedback>
                                    {getFieldDecorator('contractNo', {
                                        initialValue: dataSource.contractNo
                                    })
                                        (<Input disabled={this.state.disabled} maxLength="50" />)}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="联系人" hasFeedback>
                                    {getFieldDecorator('contact', {
                                        rules: [{ required: true, message: '请输入联系人！' }],
                                        initialValue: dataSource.contact
                                    })(<Input disabled={this.state.disabled} maxLength="20" />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="联系人岗位" hasFeedback>
                                    {getFieldDecorator('contactPosition', {
                                        rules: [{ required: true, message: '请选择联系人岗位！' }],
                                        initialValue: dataSource.contactPosition
                                    })(<BizParams disabled={this.state.disabled} sprCode="position" />)}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="固定电话" hasFeedback>
                                    {getFieldDecorator('telephone', {
                                        initialValue: dataSource.telephone
                                    })(<Input disabled={this.state.disabled} maxLength="20" />)}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="移动电话" hasFeedback>
                                    {getFieldDecorator('mobile', {
                                        initialValue: dataSource.mobile
                                    })(<Input disabled={this.state.disabled} maxLength="20" />)}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="邮箱" hasFeedback>
                                    {getFieldDecorator('email', {
                                        initialValue: dataSource.email
                                    })(<Input disabled={this.state.disabled} maxLength="20" />)}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <FormItem {...layoutAddress} label="地址" hasFeedback>
                                    {getFieldDecorator('address', {
                                        initialValue: dataSource.address
                                    })(<Input disabled={this.state.disabled} maxLength="200" />)}
                                </FormItem>
                            </Col>
                        </Row>


                        <Row>
                            <Col span={24}>
                                <FormItem {...layoutAddress} label="备注" hasFeedback>
                                    {getFieldDecorator('memo', {
                                        rules: [{
                                            required: false, message: '请输入备注',
                                        }],
                                        initialValue: dataSource.memo
                                    })(
                                        <Input.TextArea disabled={this.state.disabled} maxLength="500" autosize={{ minRows: 3, maxRows: 5 }} />
                                        )}
                                </FormItem>
                            </Col>
                        </Row>

                        {this.state.isAllocation ?
                            <RightBox resource={RightConstants.COMPANY.COMPANY_ALLOCALION_GDUSER}>
                                <Row>
                                    <Col span={12}>
                                        <FormItem {...formItemLayout} label="操作员分配" hasFeedback>
                                            {getFieldDecorator('gdUser', {
                                                rules: [{
                                                    required: true, message: '请选择操作员！',
                                                }],
                                                initialValue: dataSource.gdUser ? dataSource.gdUser + "" : undefined
                                            })(
                                                <RoleSelect role={Constants.ROLE.GD_MAN} disabled={!this.state.disabled} style={{ width: '100%' }} />

                                                )}
                                        </FormItem>
                                        <FormItem {...formItemLayout} label="业务员分配" hasFeedback>
                                            {getFieldDecorator('ywUser', {
                                                rules: [{
                                                    required: true, message: '请选择业务员！',
                                                }],
                                                initialValue: dataSource.ywUser ? dataSource.ywUser + "" : undefined
                                            })(
                                                <RoleSelect role={Constants.ROLE.SALES_MAN} disabled={!this.state.disabled} style={{ width: '100%' }} />

                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={9}>
                                        <Button type="primary" icon="className" size={'default'} disabled={!this.state.disabled} onClick={this.handleSave.bind(this)}
                                        // style={{display: this.props.disabled ? 'none' : 'inline-block', marginLeft:10 }}
                                        >确认分配</Button>
                                    </Col>
                                </Row>
                            </RightBox>
                            : ""}
                        {
                            this.props.chart ?
                                <Tabs tabPosition={'top'}>
                                    <TabPane tab="历史利润" key="1">
                                        <Chart height={300} data={dv} forceFit disabled={this.props.disabled} style={{ marginTop: 20 }}>
                                            <Axis name="月份" />
                                            <Axis name="业绩" />
                                            <Legend position="bottom" />
                                            <Tooltip crosshairs={{ type: "y" }} />
                                            <Geom type='interval' position="月份*业绩" color={'name'} adjust={[{ type: 'dodge', marginRatio: 1 / 32 }]} />
                                        </Chart>
                                    </TabPane>
                                </Tabs> : ""
                        }

                        {
                            this.props.product ?
                                <div>
                                    <Row>
                                        <Col span={3} style={{ float: 'right', display: this.state.disabled || !this.props.product ? 'none' : 'inline-block' }}>
                                            <RightBox resource={RightConstants.COMPANY.COMPANY_PRODUCT_ADD}><Button type="primary" icon="plus" size={'default'}
                                                disabled={this.state.disabled}
                                                onClick={this.handleOpenProductDetail.bind(this, false, { cid: dataSource.id })}
                                            >新增产品</Button></RightBox>
                                        </Col>
                                    </Row>
                                    <Tabs tabPosition={'top'}>
                                        <TabPane tab="外贸产品" key="1">
                                            <Table
                                                rowKey={record => record.id}
                                                loading={this.props.loading}
                                                dataSource={this.state.productList}
                                                columns={columns}
                                                bordered={true}
                                                size={'middle'}
                                                scroll={{ x: true }}
                                                style={{ marginTop: 20 }}
                                                pagination={false} />
                                        </TabPane>
                                    </Tabs>
                                </div>: ""
                        }

                        {
                            this.props.showMarketTable ?
                                <div>
                                    <Row>
                                        <Col span={3} style={{ float: 'right', display: this.state.marketDisabled ? 'none' : 'inline-block' }}>
                                            <RightBox resource={RightConstants.COMPANY.COMPANY_MARKETINFO_ADD}><Button type="primary" icon="plus" size={'default'}
                                                onClick={this.handleOpenMarketDetail.bind(this, false, { cid: dataSource.id })}
                                            >新增线索</Button></RightBox>
                                        </Col>
                                    </Row>
                                    <Tabs tabPosition={'top'}>
                                        <TabPane tab="营销线索" key="1">
                                            <Table
                                                rowKey={record => record.id}
                                                loading={this.props.marketLoading}
                                                dataSource={this.props.market.marketInfosList ? this.props.market.marketInfosList : []}
                                                columns={this.marketColumns}
                                                bordered={true}
                                                size={'middle'}
                                                scroll={{ x: true }}
                                                style={{ marginTop: 20 }}
                                                pagination={this.props.market.page} />
                                        </TabPane>
                                    </Tabs>
                                </div> : ""
                        }
                    </Form>
                </Modal>
                <ProductDetail wrappedComponentRef={(inst) => this.productDetail = inst} handleAddOrUpdateProduct={this.handleAddOrUpdateProduct} />
                <MarketDetail wrappedComponentRef={(inst) => this.marketDetail = inst} />
            </div>
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.company, marketLoading: state.loading.models.market, market: state.market
    };
}

export default connect(mapStateToProps)(companyDetail);